package cn.jeeweb.web.modules.sys.controller;

import cn.jeeweb.common.query.data.Condition;
import cn.jeeweb.common.utils.FastJsonUtils;
import cn.jeeweb.web.aspectj.annotation.Log;
import cn.jeeweb.web.modules.sys.entity.SysUserConfig;
import cn.jeeweb.web.modules.sys.service.ISysConfigService;
import cn.jeeweb.web.modules.sys.entity.SysConfig;
import cn.jeeweb.common.http.Response;
import cn.jeeweb.common.mvc.annotation.ViewPrefix;
import cn.jeeweb.common.mvc.controller.BaseBeanController;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.query.annotation.PageableDefaults;
import cn.jeeweb.common.query.data.PropertyPreFilterable;
import cn.jeeweb.common.query.data.Queryable;
import cn.jeeweb.common.query.utils.QueryableConvertUtils;
import cn.jeeweb.common.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.modules.sys.service.ISysUserConfigService;
import cn.jeeweb.web.utils.PageRequest;
import cn.xjzn.framework_Core.ModuleActionType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @description: sys_config控制器
 */

@RestController
@RequestMapping("/sys/config")
@ViewPrefix("modules/SysConfig")
//@RequiresPathPermission("sys:config")
@Log(title = "sys_config")
public class SysConfigController extends BaseBeanController<SysConfig> {
	@Autowired
	private ISysConfigService sysConfigService;

	@Autowired
	private ISysUserConfigService sysUserConfigService;


	@GetMapping
	@RequiresMethodPermissions("view")
	public ModelAndView list(Model model, HttpServletRequest request, HttpServletResponse response) {
		return displayModelAndView("list");
	}

	/**
	 * 根据页码和每页记录数，以及查询条件动态加载数据
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
	@PageableDefaults(sort = "id=desc")
	@Log(logType = ModuleActionType.SELECT)
//	@RequiresMethodPermissions("list")
	public void ajaxList(PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,HttpServletResponse response) throws IOException {
		EntityWrapper<SysConfig> entityWrapper = new EntityWrapper<>(entityClass);
		String name= request.getParameter("name");
		if (!StringUtils.isEmpty(name)){
			entityWrapper.like("name",name);
		}
		String code= request.getParameter("code");
		if (!StringUtils.isEmpty(code)){
			entityWrapper.like("code",code);
		}
//		entityWrapper.setSqlSelect(new String[]{"id","name","code","value"});//设置查询字段
//		entityWrapper.eq(true,"name","1");
//		entityWrapper.eq(true,"code","2");
//		entityWrapper.in(true,"id",new String[]{"1","2"});
//		entityWrapper.between(true,"id",1,3);
//		entityWrapper.notBetween(true,"id",1,3);
//		entityWrapper.
//		entityWrapper.allEq()
//		entityWrapper.like(true,"name","1%");
//		entityWrapper.notLike(true,"name","1%");
		propertyPreFilterable.addQueryProperty(new String[]{"id","name","code","value","isSys","remarks","createBy","createDate","updateBy","updateDate","delFlag"});
		// 预处理
//		queryable.addCondition("");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		// 预处理
		Page pageBean = sysConfigService.selectPage(PageRequest.getPage(),entityWrapper);
		FastJsonUtils.print(pageBean);
//		return Response.ok(null,pageBean);
	}

	
	@GetMapping(value = "add")
	public ModelAndView add(Model model, HttpServletRequest request, HttpServletResponse response) {
		model.addAttribute("data", new SysConfig());
		return displayModelAndView ("edit");
	}

	@PostMapping("add")
	@Log(logType = ModuleActionType.INSERT)
//	@RequiresMethodPermissions("add")
	public Response add(SysConfig entity, BindingResult result,
						   HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		EntityWrapper<SysConfig> entityWrapper = new EntityWrapper<>(SysConfig.class);
		entityWrapper.eq("code",entity.getCode());
		SysConfig old = sysConfigService.selectOne(entityWrapper);
		if(old != null){
			return Response.error("保存失败，参数配置Code值已存在");
		}else{
			sysConfigService.insert(entity);
			return Response.ok("添加成功");
		}

	}

	@GetMapping(value = "{id}/update")
	public ModelAndView update(@PathVariable("id") String id, Model model, HttpServletRequest request,
							   HttpServletResponse response) {
		SysConfig SysConfig = sysConfigService.selectById(id);
		model.addAttribute("data", SysConfig);
		return displayModelAndView ("edit");
	}

	@PostMapping("{id}/update")
	@Log(logType = ModuleActionType.UPDATE)
//	@RequiresMethodPermissions("update")
	public Response update(SysConfig entity, BindingResult result,
						   HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		EntityWrapper<SysConfig> entityWrapper = new EntityWrapper<>(SysConfig.class);
		entityWrapper.eq("code",entity.getCode());
		SysConfig old = sysConfigService.selectOne(entityWrapper);
		if(old != null && !old.getId().equals(entity.getId())){
			return Response.error("保存失败，字典分组Code值已存在");
		}else{
			sysConfigService.insertOrUpdate(entity);
			return Response.ok("更新成功");
		}
	}

	@PostMapping("{id}/delete")
	@Log(logType = ModuleActionType.DELETE)
//	@RequiresMethodPermissions("delete")
	public Response delete(@PathVariable("id") String id) {
		sysConfigService.deleteById(id);
		return Response.ok("删除成功");
	}

	@PostMapping("batch/delete")
	@Log(logType = ModuleActionType.DELETE)
//	@RequiresMethodPermissions("delete")
	public Response batchDelete(@RequestParam("ids") String[] ids) {
		List<String> idList = java.util.Arrays.asList(ids);
		sysConfigService.deleteBatchIds(idList);
		return Response.ok("删除成功");
	}

	@RequestMapping(value = "getConfigList", method = { RequestMethod.GET, RequestMethod.POST })
	@Log(logType = ModuleActionType.SELECT)
	public void getConfigList(String userId){
		EntityWrapper<SysConfig> entityWrapper = new EntityWrapper<>(SysConfig.class);
		List<SysConfig> sysConfigList = sysConfigService.selectList(entityWrapper);

		EntityWrapper<SysUserConfig> sysUserConfigEntityWrapper = new EntityWrapper<>(SysUserConfig.class);
		sysUserConfigEntityWrapper.eq("createBy",userId);
		List<SysUserConfig> sysUserConfigs = sysUserConfigService.selectList(sysUserConfigEntityWrapper);

		if(sysConfigList != null && sysConfigList.size() > 0){
			if(sysUserConfigs != null && sysUserConfigs.size() > 0){
				sysUserConfigs.forEach(t ->{
					sysConfigList.removeIf(r -> r.getCode().equals(t.getCode()) && r.getName().equals(t.getName()));
				});
			}
			List<SysConfig> result = objectTransform(sysUserConfigs);
			sysConfigList.addAll(result);
		}
		FastJsonUtils.print(sysConfigList);
	}

	public List<SysConfig> objectTransform(List<SysUserConfig> sysUserConfigs){
		List<SysConfig> list = new ArrayList<SysConfig>();
		if(sysUserConfigs != null && sysUserConfigs.size() > 0){
			for(SysUserConfig userConfig : sysUserConfigs){
				SysConfig sysConfig = new SysConfig();
				sysConfig.setCode(userConfig.getCode());
				sysConfig.setName(userConfig.getName());
				sysConfig.setValue(userConfig.getValue());
				sysConfig.setCreateBy(userConfig.getCreateBy());
				sysConfig.setCreateDate(userConfig.getCreateDate());
				sysConfig.setUpdateBy(userConfig.getUpdateBy());
				sysConfig.setUpdateDate(userConfig.getUpdateDate());
				sysConfig.setDelFlag(userConfig.getDelFlag());
				sysConfig.setRemarks(userConfig.getRemarks());
				sysConfig.setUpdater(userConfig.getUpdater());
				sysConfig.setCreater(userConfig.getCreater());
				list.add(sysConfig);
			}
		}
		return list;
	}
}